package com.example.xiaoyuan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.xiaoyuan.pojo.Admin;
import com.example.xiaoyuan.pojo.LoginForm;
import com.example.xiaoyuan.pojo.Student;
import com.example.xiaoyuan.pojo.Teacher;
import com.example.xiaoyuan.service.AdminService;
import com.example.xiaoyuan.service.StudentService;
import com.example.xiaoyuan.service.TeacherService;
import com.example.xiaoyuan.utils.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.UUID;


@Api(tags = "系统控制器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(
            @RequestHeader("token") String token,
            @PathVariable String oldPwd,
            @PathVariable String newPwd
    ){
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) return Result.fail().message("token失效，请重新登录！");

        //获取用户id和类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        oldPwd = MD5.encrypt(oldPwd);
        newPwd = MD5.encrypt(newPwd);

        switch (userType){
            case 1:
                LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Admin::getId, userId.intValue());
                queryWrapper.eq(Admin::getPassword, oldPwd);
                Admin admin = adminService.getOne(queryWrapper);

                if (admin != null){
                    admin.setPassword(newPwd);
                    adminService.saveOrUpdate(admin);
                }else {
                    return Result.fail().message("原密码错误");
                }
                break;
            case 2:
                LambdaQueryWrapper<Student> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(Student::getId, userId.intValue());
                queryWrapper2.eq(Student::getPassword, oldPwd);
                Student student = studentService.getOne(queryWrapper2);

                if (student != null){
                    student.setPassword(newPwd);
                    studentService.saveOrUpdate(student);
                }else {
                    return Result.fail().message("原密码错误");
                }
                break;
            case 3:
                LambdaQueryWrapper<Teacher> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(Teacher::getId, userId.intValue());
                queryWrapper3.eq(Teacher::getPassword, oldPwd);
                Teacher teacher = teacherService.getOne(queryWrapper3);

                if (teacher != null){
                    teacher.setPassword(newPwd);
                    teacherService.saveOrUpdate(teacher);
                }else {
                    return Result.fail().message("原密码错误");
                }
                break;
        }
        return Result.ok();
    }



    /**
     * 图片上传
     * @param multipartFile
     * @param request
     * @return URL图片路径
     */
    @PostMapping("/headerImgUpload")
    public Result  headerImgUpload(
            @RequestPart("multipartFile") MultipartFile multipartFile,
            HttpServletRequest request){

        String uuid = UUID.randomUUID().toString().replace("-","").toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String newFileName = uuid.concat(originalFilename.substring(i));
        // 保存文件
//        String portraitPath = "D:\\WorkSpace\\IDEA\\JavaEE\\xiaoyuan\\target\\classes\\public\\upload\\".concat(newFileName);
        String portraitPath = "/www/wwwroot/SpringBoot/xiaoyuan/resource".concat(newFileName);
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 响应图片路径
        String path = "upload/".concat(newFileName);
        return Result.ok(path);
    }

    @GetMapping("/getInfo")
    public Result getInfoByToken(@RequestHeader("token") String token){

        boolean expiration = JwtHelper.isExpiration(token);
        //判断token是否过期
        if (expiration){
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }

        //从token中解析出 用户id 和用户的类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        LinkedHashMap<String , Object> map = new LinkedHashMap<>();

        switch (userType){
            case 1:
                Admin admin = adminService.getAdminById(userId);
                map.put("userType", 1);
                map.put("user", admin);
                break;
            case 2:
                Student student = studentService.getStudentById(userId);
                map.put("userType", 2);
                map.put("user", student);
                break;
            case 3:
                Teacher teacher = teacherService.getTeacherById(userId);
                map.put("userType", 3);
                map.put("user", teacher);
                break;
        }

        return Result.ok(map);
    }


    /**
     * 用户登录，判断是哪种类型
     * @param loginForm
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request){

        //验证码
        HttpSession session = request.getSession();
        String sessionVerifiCode = (String) session.getAttribute("verifiCode");

        String loinverifiCode = loginForm.getVerifiCode();

        if ("".equals(sessionVerifiCode) || null == sessionVerifiCode){
            return Result.fail().message("验证码失效，请刷新后重试");
        }
        if (!sessionVerifiCode.equalsIgnoreCase(loinverifiCode)){
            return Result.fail().message("验证码有误，请重新输入");
        }
        //从session移除验证码
        session.removeAttribute("verifiCode");

        //分用户类型进行校验
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        switch (loginForm.getUserType()){
            case 1:
                try {
                   Admin admin = adminService.login(loginForm);
                   if(admin != null){
                       map.put("token", JwtHelper.createToken(admin.getId().longValue(), 1));
                   }else {
                       throw new RuntimeException("用户名或者密码有误");
                   }
                    return Result.ok(map);
                } catch (RuntimeException e){
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case 2:
                try {
                    Student student = studentService.login(loginForm);
                if(student != null){
                    map.put("token", JwtHelper.createToken(student.getId().longValue(), 2));
                }else {
                    throw new RuntimeException("用户名或者密码有误");
                }
                    return Result.ok(map);
            } catch (RuntimeException e){
                e.printStackTrace();
                return Result.fail().message(e.getMessage());
            }

            case 3:
                try {
                    Teacher teacher = teacherService.login(loginForm);
                    if(teacher != null){
                        map.put("token", JwtHelper.createToken(teacher.getId().longValue(), 3));
                    }else {
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e){
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }
        return Result.fail().message("没有找到该用户");
    }


    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        //获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        //获取图片的验证码
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
        // 将验证码文本放入session域,为下一次验证做准备
        request.getSession().setAttribute("verifiCode", verifiCode);

        // 将验证码图片响应给浏览器
        try {
            ImageIO.write(verifiCodeImage,"JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
